<?php
require('Base.php');
class Login extends Base
{
	/**
	 * 获取用户信息
	 * @param String $username 用户名
	 * @return Array
	 */
	public function getUserInfo(string $username)
	{
		// 预定义返回数据
		$res = $this->api_res;

		// 获取数据库连接
		$con = $this->connectDB();
		// 获取用户信息
		$db_prefix = $this->config['db']['prefix'];
		$data = [
			':username' => $username
		];
		$sql = "SELECT * FROM `{$db_prefix}user` WHERE `username`=:username AND `usable`=1 LIMIT 1;";
		$stm = $con->prepare($sql);
		$query = $stm->execute($data);
		if($query === false)
		{
			$res['err_msg'] = $stm->errorInfo();
			return $res;
		}
		$user_info = $stm->fetch(PDO::FETCH_ASSOC);
		if($user_info === false)
		{
			$res['err_msg'] = '用户不存在';
			return $res;
		}

		$res['status'] = 1;
		$res['data'] = $user_info;
		return $res;
	}


}
/* ============================= CLASS FINISHED  ============================= */

	if( !($_POST) )
	{
		header('HTTP/1.1 403 Forbidden');
		die();
	}

	$Login = new Login();
	// 获取用户名、密码
	$username = trim( strval($_POST['username']) );
	if(!$username)
	{
		$Login->error('用户名为空！');
	}
	$pwd = trim( strval($_POST['pwd']) );
	if(!$pwd)
	{
		$Login->error('密码为空！');
	}

	// 获取用户信息
	$get_user_info = $Login->getUserInfo($username);
	if($get_user_info['status'] !== 1)
	{
		$err_msg = $get_user_info['err_msg'];
		$Login->error($err_msg);
	}
	$user_info = $get_user_info['data'];

	// 计算密文密码
	$salt = $user_info['salt'];
	$true_pwd = $Login->getCryptedPassword($pwd, $salt);
	// 检查密码
	if($true_pwd !== $user_info['password'])
	{
		$Login->error('密码错误！');
	}

	// 生成session
	session_start();
	$_SESSION['user'] = $username;
	header('Location: ./index.php');

?>
